package com.hcbd.tdwt.ui.xingyu.activity;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;


import com.hcbd.tdwt.R;
import com.hcbd.tdwt.base.BaseActivity;
import com.hcbd.tdwt.base.BdManager;
import com.hcbd.tdwt.base.BeidouBoxParams;
import com.pangu.bdsdk2021.bluetooth.BluetoothManage;
import com.pangu.bdsdk2021.entity.terminalone.BDICInfo;
import com.pangu.bdsdk2021.entity.terminalthree.BDSXXInfo;
import com.hcbd.tdwt.ui.xingyu.adapter.BluetoothAdapter;

import com.hcbd.tdwt.ui.xingyu.vo.BDBoxVO;

import com.raizlabs.android.dbflow.sql.language.SQLite;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.OnActivityResult;
import org.androidannotations.annotations.ViewById;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

@SuppressLint("NonConstantResourceId")
@EActivity(R.layout.activity_search_bluetooth)
public class SearchBluetoothActivity extends BaseActivity  implements BdManager.BlueToothInterface{
    @ViewById(R.id.my_device_tv)
    TextView myDeviceTv;

    @ViewById(R.id.my_device_rv)
    RecyclerView myDeviceRv;
    @ViewById(R.id.other_device_rv)
    RecyclerView otherDeviceRv;
    @ViewById
    ImageButton headLeft;
   // private BluetoothBoxAdapter boxAdapter;
    private BluetoothAdapter otherBluetoothAdapter;
    private BluetoothAdapter myBluetoothAdapter;
    private List<BluetoothDevice>otherBluetoothDevices;
    private List<BluetoothDevice>myBluetoothDevices;
    private List<BDBoxVO> boxVOList;
    private final int BOX_DEL_INFO=10;
    @AfterViews
    protected void init() {
        initMsgRegister();
        myDeviceRv.setVisibility(View.GONE);
        myDeviceTv.setVisibility(View.GONE);
        boxVOList = SQLite.select().from(BDBoxVO.class).queryList();
        currentDevice=new BDBoxVO();
        otherBluetoothDevices=new ArrayList<>();
        myBluetoothDevices=new ArrayList<>();
        initMyDeviceData();
        initOtherDeviceData();
        BdManager.getInstance().setBlueToothInterface(this);
        BluetoothManage.getInstance().startDiscovery();
    }


    private BluetoothDevice currentBluetoothDevice;
    //连接过的设备连接
    public void initMyDeviceData(){
        if(myBluetoothDevices==null||myBluetoothDevices.size()==0){
            myDeviceRv.setVisibility(View.GONE);
            myDeviceTv.setVisibility(View.GONE);
        }
        if(myBluetoothAdapter==null){
            myBluetoothAdapter=new BluetoothAdapter(this, myBluetoothDevices,true);
            myBluetoothAdapter.setHasStableIds(true);
        }else{
            myBluetoothAdapter.notifyDataSetChanged(myBluetoothDevices);
            return;
        }
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 1);
        myDeviceRv.setLayoutManager(gridLayoutManager);
        myDeviceRv.setAdapter(myBluetoothAdapter);
        myBluetoothAdapter.setOnItemClickListener(new BluetoothAdapter.OnItemClickListener() {
            @Override
            public void onClick(BluetoothDevice bluetoothDevice) {
                showLoading("连接蓝牙中");
                BluetoothManage.getInstance().connectGatt(bluetoothDevice);
            }

            @Override
            public void onInfo(BluetoothDevice bluetoothDevice) {

                Intent intent=new Intent();
                intent.setClass(SearchBluetoothActivity.this,BluetoothInfoActivity_.class);
                intent.putExtra("adders",bluetoothDevice.getAddress());
                currentBluetoothDevice=bluetoothDevice;
                startActivityForResult(intent,BOX_DEL_INFO);
            }
        });
    }
    @OnActivityResult(BOX_DEL_INFO)
    void result(int resultCode){
        if(resultCode==RESULT_OK){
            toast("已删除,正在重新加载");
            boxVOList = SQLite.select().from(BDBoxVO.class).queryList();
            if(currentBluetoothDevice!=null){
                myBluetoothDevices.remove(currentBluetoothDevice);
            }
            initMyDeviceData();
            BluetoothManage.getInstance().startDiscovery();
        }
    }
    //新的设备列表
    public void initOtherDeviceData(){
        if(otherBluetoothAdapter==null){
            otherBluetoothAdapter=new BluetoothAdapter(this,otherBluetoothDevices,false);
            otherBluetoothAdapter.setHasStableIds(true);
        }else{
            otherBluetoothAdapter.notifyDataSetChanged(otherBluetoothDevices);
            return;
        }
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 1);
        otherDeviceRv.setLayoutManager(gridLayoutManager);
        otherDeviceRv.setAdapter(otherBluetoothAdapter);
        otherBluetoothAdapter.setOnItemClickListener(new BluetoothAdapter.OnItemClickListener() {
            @Override
            public void onClick(BluetoothDevice bluetoothDevice) {
                showLoading("连接蓝牙中");
                BluetoothManage.getInstance().connectGatt(bluetoothDevice);

            }
            @Override
            public void onInfo(BluetoothDevice bluetoothDevice) {

            }
        });
    }


    @Click
    void headLeft(){
        finish();
    }

    @Override
    public void onScanningResult(List<BluetoothDevice> list, BluetoothDevice bluetoothDevice) {
        if (bluetoothDevice.getName() == null) return;
        boolean isExist = false;
        for (int i = 0; i < boxVOList.size(); i++) {
            if (bluetoothDevice.getAddress().equals(boxVOList.get(i).macAdders)) {
                isExist = true;
                break;
            }
        }
        if(isExist&&!myBluetoothDevices.contains(bluetoothDevice)){
            myDeviceRv.setVisibility(View.VISIBLE);
            myDeviceTv.setVisibility(View.VISIBLE);
            myBluetoothDevices.add(bluetoothDevice);
            initMyDeviceData();
        }else if(!isExist&&!otherBluetoothDevices.contains(bluetoothDevice)){
            otherBluetoothDevices.add(bluetoothDevice);
            initOtherDeviceData();
        }
    }
    public BDBoxVO currentDevice;
    @Override
    public void onConnectSucceed(BluetoothDevice bluetoothDevice) {
        currentDevice.bluetoothName=bluetoothDevice.getName();
        currentDevice.macAdders=bluetoothDevice.getAddress();
        BeidouBoxParams.blueName=bluetoothDevice.getName();
        runOnUiThread(() -> {
            toast("蓝牙连接成功");
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        BluetoothManage.getInstance().stopDiscovery();
    }
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true, priority = 2)
    public void eventBus(BDSXXInfo bdsxxInfo){
        currentDevice.bdCardNum= BeidouBoxParams.userCardNumber;
        currentDevice.cardMode= "BD3";
        BDBoxVO.upData(currentDevice);
        hideLoading();
        finish();
    }
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true, priority = 2)
    public void eventBus(BDICInfo bdicInfo){
        currentDevice.bdCardNum= BeidouBoxParams.userCardNumber;
        currentDevice.cardMode= "BD2";
        BDBoxVO.upData(currentDevice);
        hideLoading();
        finish();
    }
}
